/** ###################################################################
**     Filename  : vbat.C
**     Project   : Motologger_v2
**     Processor : MC9S12XD256BMFU
**     Compiler  : CodeWarrior HCS12X C Compiler
**     Date/Time : 11/14/2009, 6:49 PM
**     Contents  :
**         User source code
**
**     (c) Copyright UNIS, spol. s r.o. 1997-2007
**     UNIS, spol. s r.o.
**     Jundrovska 33
**     624 00 Brno
**     Czech Republic
**     http      : www.processorexpert.com
**     mail      : info@processorexpert.com
** ###################################################################*/

/* MODULE vbat */
#include "vbat.h"
#include "Vbat_Gear_ADC.h"


#define VBAT_ADC_CHAN 0                

#define VBAT_AVG 0 //enable/disable averaging

#if VBAT_AVG 
	#define VBAT_NUM2AVG 8
	unsigned short vbat_vals[VBAT_NUM2AVG];
#endif

unsigned short vbat_adc; //raw adc value for vbat

//returns battery voltage in millivolts
unsigned short Vbat_GetVal(void){
  unsigned short vbat_mv; 
  
#if VBAT_AVG
  unsigned short vbatAvgADCVal=0;  
  unsigned char avgIndex;
  
  for(avgIndex = 0;avgIndex<VBAT_NUM2AVG;avgIndex++){
		vbatAvgADCVal+=vbat_vals[avgIndex];  		
  }
	vbat_adc=vbatAvgADCVal/VBAT_NUM2AVG;
#endif

  vbat_mv =(vbat_adc*41)/5; //system dependent calibration

  return vbat_mv;
}

void Vbat_Update(void){

#if VBAT_AVG
  
  static unsigned char avgIndex;
  Vbat_Gear_ADC_GetChanValue16((byte)VBAT_ADC_CHAN, &vbat_vals[avgIndex%VBAT_NUM2AVG]);
  avgIndex++;
  
#else

	Vbat_Gear_ADC_GetChanValue16((byte)VBAT_ADC_CHAN, &vbat_adc);
	
#endif  

}

/* END vbat */


